import * as uuid from 'uuid'
import { IObj } from '../interface'

interface ITable {
	column_name: string;
	column_comment: string;
}

function item(parent_id: string, prop: string, type: string, label: string) {
	return {
		doc_id: '',
		prop_id: uuid(),
		parent_id,
		prop,
		required: 1,
		type,
		optional: [],
		label: label || '',
		note: ''
	}
}

function obj(M: Map<string, string>, parent_id: string, data: IObj, tables: ITable[], arr: IObj[]) {
	for (const key in data) {
		if (data.hasOwnProperty(key)) {
			parse_api(M, parent_id, key, (data[key] as unknown as IObj), tables, arr)
		}
	}
}

function parse_api(M: Map<string, string>, parent_id: string, prop: string, data: IObj, tables: ITable[], arr: IObj[]): IObj[] {


	const type = typeof data
	if (type === 'object') {
		if (Array.isArray(data)) {
			if (typeof data[0] === 'object') {
				const root = item(parent_id, prop, 'object[]', M.get(prop))
				obj(M, root.prop_id, (data[0] as IObj), tables, arr)
				arr.push(root)
			} else {
				const root = item(parent_id, prop, 'string[]', M.get(prop))
				arr.push(root)
			}
		} else {
			const root = item(parent_id, prop, 'object', M.get(prop))
			arr.push(root)
			obj(M, root.prop_id, (data as IObj), tables, arr)
		}
	} else {
		if (type === 'number') {
			arr.push(item(parent_id, prop, 'number', M.get(prop)))
		} else {
			arr.push(item(parent_id, prop, 'string', M.get(prop)))
		}
	}

	return arr
}

export default function main(parent_id: string, prop: string, data: IObj, tables: ITable[]): IObj[] {
	const M1 = new Map() as Map<string, string>;
	M1.set('request', '请求参数')
	M1.set('response', '返回数据')
	const M = tables.reduce((p, c) => {
		if (c.column_comment) {
			p.set(c.column_name, c.column_comment)
		}
		return p;
	}, M1)
	console.log(prop, ':  ', M.get(prop))

	return parse_api(M, parent_id, prop, data, tables, [])
}
